<script setup lang='ts'>
// 导入
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus'
import userAPI from '@/utils/user/user'
import settingAPI from '@/setting/setting'

import {
    Plus,
    Delete,
    Edit,
    Search,
    Upload,
    Download
} from '@element-plus/icons-vue'
// 定义变量
const formData = reactive({
    userData: [
        {
            username: '',
            first_name: '',
            last_name: '',
            is_active: true,
            is_superuser: false,
            date_joined: ''
        }
    ],
    searchusername: '',
    addDialogVisible: false,
    importDialogVisible: false,
    editDialogVisible: false,
    usertem: {
        password: '',
        checkPass: '',
        username: '',
    }

})

const url = '/per-manage/users/'
const userrow = ref()
// 获取数据
const getuserstem = async () => {
    const users = await userAPI.getusers(url)
    formData.userData = users
}
getuserstem()

// 函数
const addUserDailog = () => {
    formData.addDialogVisible = true
}

const deleteUser = async (row: any) => {
    await userAPI.deleteuser(url + row.id + '/')
    ElMessage({
        message: '你已删除成功！',
        type: 'error',
    })
    getuserstem()
}

const editUser = (row: any) => {
    userrow.value = row
    formData.editDialogVisible = true
}

const editDialogUser = async () => {
    delete userrow.value.password
    const userurl = url + userrow.value.id + '/'
    await userAPI.edituser(userurl, userrow.value)
    ElMessage({
        message: '恭喜你' + userrow.value.username + '已修改成功！',
        type: 'success',
    })
    getuserstem()
    userrow.value = ''
    formData.editDialogVisible = false
}

const importUserDialog = () => {
    formData.importDialogVisible = true
}

const importUser = async (file: any) => {
    // 文件在axiox中一般封装在formdata类中
    // 1.定义formData类
    let fileReq = new FormData()
    // 2.把文件装在formData的容器中
    fileReq.append('file', file.file)
    // 请求
    const importurl = url + 'importUser/'
    await userAPI.importUser(importurl, fileReq).then(() => {
        ElMessage({
            message: '恭喜你导入成功！',
            type: 'success',
        })
    }).catch((err: any) => {
        ElMessage({
            message: '导入失败:' + err,
            type: 'success',
        })
    })
    getuserstem()
    formData.editDialogVisible = false

}
const dowloadModleFile = () => {
    try {
        let url = settingAPI.BACK_URL + 'media/model/用户名创建模板.xlsx';
        let elementIftrame = document.createElement("iframe");
        elementIftrame.src = url;
        elementIftrame.style.display = "none";
        document.body.appendChild(elementIftrame);
    } catch (error) {
        console.log(error);
    }
}

// 对话框处理
const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码！'))
    } else if (value !== ruleForm.password) {
        callback(new Error("两次输入的密码不一样！"))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    password: '',
    checkPass: '',
    username: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
    username: [
        { required: true, message: '请输入用户名！', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码！！', trigger: 'blur' },
    ],
    checkPass: [{ validator: validatePass, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            await userAPI.adduser(url + 'adduser/', ruleForm)
            getuserstem()
            ruleForm.password = ''
            ruleForm.username = ''
            ruleForm.checkPass = ''
            formData.addDialogVisible = false
            ElMessage({
                message: '恭喜你添加的用户已经成功！',
                type: 'success',
            })

        } else {
            ElMessage({
                message: '你提交的信息有误，请重新输入！',
                type: 'error',
            })
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
<template>
    <!-- 标题 -->
    <div class="usertitle">
        用户管理
    </div>
    <!-- 操作 -->
    <div class="optionsper">
        <el-row class="row-bg" justify="space-between">
            <el-col :span="6" class="centerbutton">
                <div>
                    <el-input v-model="formData.searchusername" style="width: 240px" placeholder="请输入用户名进行查询！"
                        :prefix-icon="Search" />
                </div>
            </el-col>
            <el-col :span="6" class="centerbutton">
                <el-button type="primary" :icon="Plus" round @click="addUserDailog">增加用户</el-button>
                <el-button type="warning" :icon="Upload" round @click="importUserDialog">导入</el-button>
            </el-col>

        </el-row>
    </div>
    <!-- 表格 -->
    <div>
        <el-table :data="formData.userData" border style="width: 100%">
            <el-table-column type="index" label='序号' width="70" />
            <el-table-column prop="username" label="用户名" width="180" />
            <el-table-column prop="first_name" label="姓" width="180" />
            <el-table-column prop="last_name" label="名" width="180" />
            <el-table-column prop="is_active" label="是否启用" />
            <el-table-column prop="is_staff" label="是否超级用户" />
            <el-table-column prop="date_joined" label="创建时间" />
            <el-table-column align="center" label='操作'>
                <template #default="scope">
                    <el-button size="small" :icon="Edit" type="success" @click="editUser(scope.row)" circle />
                    <el-button size="small" :icon="Delete" type="danger" @click="deleteUser(scope.row)" circle />
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 对话框 -->
    <!-- 关于增加用户的对话框 -->
    <el-dialog v-model="formData.addDialogVisible" title="添加登录用户" width="500" align-center>
        <span>
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="ruleForm.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item class="usersubmit">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        增加
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </span>
    </el-dialog>
    <!-- 用户修改对话框 -->
    <el-dialog v-model="formData.editDialogVisible" title="修改登录用户" width="500" align-center>
        <span>
            <el-form :model="userrow" class="demo-ruleForm">
                <el-form-item label="用户名">
                    <el-input v-model="userrow.username" />
                </el-form-item>
                <el-form-item label="姓">
                    <el-input v-model="userrow.first_name" />
                </el-form-item>
                <el-form-item label="名">
                    <el-input v-model="userrow.last_name" />
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-input v-model="userrow.is_active" />
                </el-form-item>
                <el-form-item label="是否超级用户">
                    <el-input v-model="userrow.is_superuser" />
                </el-form-item>
                <el-form-item class="usersubmit">
                    <el-button type="primary" @click="editDialogUser">
                        修改
                    </el-button>
                </el-form-item>
            </el-form>
        </span>
    </el-dialog>
    <!-- 关于导入用户的对话框 -->
    <el-dialog v-model="formData.importDialogVisible" title="批量导入用户" width="500" align-center>
        <span>
            <div class="downloadimportmodel">
                <el-button :icon="Download" @click="dowloadModleFile" round type="success" size="large">下载模板</el-button>
            </div>
        </span>
        <span>
            <el-upload class="upload-demo" drag :http-request='importUser' multiple>
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处 <em>或单击此处上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        请上传EXCEL文件！
                    </div>
                </template>
            </el-upload>
        </span>
    </el-dialog>
</template>
<style scoped>
.optionsper {
    background: #fff;
    margin: 10px 0;
    height: 40px;
}

.usertitle {
    background: #fff;
    margin: 10px 0;
    height: 50px;
    text-align: center;
    font-size: 30px
}

.row-bg {
    text-align: center;
}

.centerbutton {
    margin-top: 5px;
}

.downloadimportmodel {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60px;
}

.el-upload__tip {
    color: red;
    font-size: 20px;
    text-align: center
}

.usersubmit {
    margin-left: 40%;
}
</style>